package com.cn.lp.export.server.entity.executor;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.cn.lp.export.server.ExportResultCodes;
import com.cn.lp.export.server.base.context.ExportExceptionCreator;
import com.cn.lp.export.server.base.oss.AliyunOssManager;
import com.cn.lp.export.server.controller.CreateExportTaskRequest;
import com.cn.lp.export.server.entity.ExportTask;
import com.cn.lp.export.server.entity.ExportTaskDao;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Date;
import java.util.List;

/**
 * 阿里云OSS导出器
 * Created by qirong on 2020/10/18.
 */
public class AliyunOssExportExecutor extends BaseExportExecutor {

    @Resource
    protected AliyunOssManager aliyunOssManager;

    @Autowired
    protected ExportTaskDao exportTaskDao;

    @Override
    protected void doExport(ExportTask exportTask, List<List<Object>> excelExportDataList, List<List<String>> excelHeaderList) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        writeExcel(os, excelExportDataList, "", excelHeaderList);
        aliyunOssManager.putObject(exportTask.getExcelName(), os.toByteArray());
    }

    @Override
    public ExportResult createResultUrl(CreateExportTaskRequest createRequest) {
        String excelName = createRequest.getExcelName() + "_" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS") + ".xlsx";
        String resultUrl =  aliyunOssManager.generateObjectUrl(excelName);
        return ExportResult.of(excelName, resultUrl);
    }

    /**
     * 导出 Excel并上传阿里云 ：一个 sheet，带表头
     *
     * @param outputStream ByteArrayOutputStream
     * @param list         数据 list，每个元素为一个 BaseRowModel
     * @param sheetName    导入文件的 sheet 名
     * @param head         导出Excel文件表头
     */
    public static void writeExcel(ByteArrayOutputStream outputStream, List<List<Object>> list, String sheetName, List<List<String>> head) {
        ExcelWriter writer = new ExcelWriter(outputStream, ExcelTypeEnum.XLSX);
        Sheet sheet = new Sheet(1, 0);
        if (StringUtils.isNotEmpty(sheetName)) {
            sheet.setSheetName(sheetName);
        } else {
            sheet.setSheetName("Sheet1");
        }
        sheet.setHead(head);
        writer.write1(list, sheet);
        writer.finish();
    }
}
